package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.Bindable;
import android.databinding.ObservableArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.solidfire.gson.internal.LinkedTreeMap;
import com.umeng.socialize.ShareContent;
import com.umeng.socialize.media.UMImage;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.SaveContent;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/11/17.
 */
public class VideoDetail extends ObservableWithGoBackHandler {
    private VideoItem video;
    private int videolike;
    private int collect;
    private int videoshare;
    private int jifen;
    private Date uploaddate;
    private boolean collectflag;
    private boolean likeflag;
    private boolean attentionFlag;
    private boolean descSelected;
    private boolean commentSelected;
    private int descContentVisibility;
    private int commentContentVisibility;
    private String avatar;
    private String notespath;
    private String notesimgpath;

    //    private int collectImageSource;
//    private int likeImageSource;
    private String commentContent;
    private ListBindingAdapter<ClickMenuItem> menus;

    private ListBindingAdapter<VideoItem> videoItems;
    private ListBindingAdapter<CommentItem> commentItems;

    @Bindable
    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    @Bindable
    public String getNotespath() {
        return notespath;
    }

    public void setNotespath(String notespath) {
        this.notespath = notespath;
        notifyPropertyChanged(BR.notespath);
    }

    @Bindable
    public String getNotesimgpath() {
        return notesimgpath;
    }

    public void setNotesimgpath(String notesimgpath) {
        this.notesimgpath = notesimgpath;
        notifyPropertyChanged(BR.notesimgpath);
    }

    @Bindable
    public ListBindingAdapter<ClickMenuItem> getMenus() {
        return menus;
    }

    @Bindable
    public ListBindingAdapter<VideoItem> getVideoItems() {
        return videoItems;
    }

    @Bindable
    public ListBindingAdapter<CommentItem> getCommentItems() {
        return commentItems;
    }

    @Bindable
    public boolean isDescSelected() {
        return descSelected;
    }

    public void setDescSelected(boolean descSelected) {
        this.descSelected = descSelected;
        if (this.descSelected) {
            setCommentSelected(false);
            setCommentContentVisibility(View.GONE);
            setDescContentVisibility(View.VISIBLE);
        }
        notifyPropertyChanged(BR.descSelected);
    }

    @Bindable
    public boolean isCommentSelected() {
        return commentSelected;
    }

    public void setCommentSelected(boolean commentSelected) {
        this.commentSelected = commentSelected;
        if (this.commentSelected) {
            setDescSelected(false);
            setCommentContentVisibility(View.VISIBLE);
            setDescContentVisibility(View.GONE);
        }
    }

    @Bindable
    public VideoItem getVideo() {
        return video;
    }

    public void setVideo(VideoItem video) {
        this.video = video;
        notifyPropertyChanged(BR.video);
        // 设置所属视频时重新加载数据
        if (this.commentSelected) {
            this.loadCommentList();
        } else if (this.descSelected) {
            this.loadRelatedVieoList();
        }
    }

    @Bindable
    public int getVideolike() {
        return videolike;
    }

    public void setVideolike(int videolike) {
        this.videolike = videolike;
        notifyPropertyChanged(BR.videolike);
    }

    @Bindable
    public int getCollect() {
        return collect;
    }

    public void setCollect(int collect) {
        this.collect = collect;
        notifyPropertyChanged(BR.collect);
    }

    @Bindable
    public int getVideoshare() {
        return videoshare;
    }

    public void setVideoshare(int videoshare) {
        this.videoshare = videoshare;
        notifyPropertyChanged(BR.videoshare);
    }

    @Bindable
    public int getJifen() {
        return jifen;
    }

    public void setJifen(int jifen) {
        this.jifen = jifen;
        notifyPropertyChanged(BR.jifen);
    }

    @Bindable
    public boolean isAttentionFlag() {
        return attentionFlag;
    }

    public void setAttentionFlag(boolean attentionflag) {
        this.attentionFlag = attentionflag;
        notifyPropertyChanged(BR.attentionFlag);
    }

    @Bindable
    public Date getUploaddate() {
        return uploaddate;
    }

    public void setUploaddate(Date uploaddate) {
        this.uploaddate = uploaddate;
        notifyPropertyChanged(BR.uploadate);
    }

    @Bindable
    public int getDescContentVisibility() {
        return descContentVisibility;
    }

    public void setDescContentVisibility(int descContentVisibility) {
        this.descContentVisibility = descContentVisibility;
        if (descContentVisibility == View.VISIBLE) {

        }
        notifyPropertyChanged(BR.descContentVisibility);
    }

    @Bindable
    public int getCommentContentVisibility() {
        return commentContentVisibility;
    }

    public void setCommentContentVisibility(int commentContentVisibility) {
        this.commentContentVisibility = commentContentVisibility;
        if (this.commentContentVisibility == View.VISIBLE) {
            if (commentItems == null || commentItems.getCount() <= 0) {
                loadCommentList();
            }
        }
        notifyPropertyChanged(BR.commentContentVisibility);
    }

    @Bindable
    public boolean isCollectflag() {
        return collectflag;
    }

    public void setCollectflag(boolean collectflag) {
        this.collectflag = collectflag;
        notifyPropertyChanged(BR.collectflag);
    }

    @Bindable
    public boolean isLikeflag() {
        return likeflag;
    }

    public void setLikeflag(boolean likeflag) {
        this.likeflag = likeflag;
        notifyPropertyChanged(BR.likeflag);
    }

    @Bindable
    public String getCommentContent() {
        return commentContent;
    }

    public void setCommentContent(String commentContent) {
        this.commentContent = commentContent;
        notifyPropertyChanged(BR.commentContent);
    }

    public VideoDetail(Context context) {
        super(context);
        super.getHandler().setTitle("课程详情");
        commentSelected = false;
        descSelected = true;
        this.descContentVisibility = View.VISIBLE;
        this.commentContentVisibility = View.GONE;
//        this.likeImageSource = R.mipmap.study_like;
//        this.collectImageSource = R.mipmap.study_collect;
        this.videoItems = new ListBindingAdapter<VideoItem>(context, BR.video);
        this.commentItems = new ListBindingAdapter<CommentItem>(context, BR.comment);
        this.menus = new ListBindingAdapter<ClickMenuItem>(context, BR.menu);
        this.load();
    }

    /**
     * 从服务器加载首页数据
     */
    public void load() {
        final Context context = super.getContext();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List menuList = WebApi.getMenus(context);
                for (Object menu : menuList) {
                    LinkedTreeMap map = (LinkedTreeMap) menu;
                    ClickMenuItem item = new ClickMenuItem(context, R.layout.i_click_menu);
                    item.setCode((String) map.get("code"));
                    item.setTitle((String) map.get("title"));
                    menus.add(item);
                }
                notifyDataSetChanged(menus);
            }
        }).start();
    }

    /**
     * 加载评论列表
     */
    private void loadCommentList() {
        final Context context = super.getContext();
        commentItems.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                commentItems.setNotifyOnChange(false);
                List commentList = WebApi.getCommentList(context, "v", video.getVideoid());
                try {
                    for (Object comment : commentList) {
                        LinkedTreeMap map = (LinkedTreeMap) comment;
                        CommentItem item = new CommentItem(context, R.layout.i_comment);
                        item.setCommentType("v");
                        item.setUid(Integer.valueOf((String) map.get("uid")));
                        item.setCommenttime(Utils.getDateFromFormat(map.get("commenttime"), "yyyy-MM-dd HH:mm:ss"));
                        item.setCommentid(Utils.getIntValue(map.get("commentid")));
                        item.setCommentlike(Utils.getIntValue(map.get("commentlike")));
                        item.setCommentcontent((String) map.get("commentcontent"));
                        item.setReply(Utils.getIntValue(map.get("reply")));
                        item.setJob((String) map.get("job"));
                        item.setAvatar((String) map.get("avatar"));
                        item.setName((String) map.get("nickname"));
                        item.setIndustry((String) map.get("industry"));
                        commentItems.add(item);
                    }
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
                notifyDataSetChanged(commentItems);
            }
        }).start();
    }

    /**
     * 获取相关课程列表
     */
    private void loadRelatedVieoList() {
        final Context context = super.getContext();
        videoItems.clear(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                videoItems.setNotifyOnChange(false);
                List videoList = WebApi.getRelatedVideos(context, video.getVideoid());
                try {
                    for (Object menu : videoList) {
                        LinkedTreeMap map = (LinkedTreeMap) menu;
                        VideoItem item = new VideoItem(context, R.layout.i_study);
                        item.setUid(Utils.getIntValue(map.get("uid")));
                        item.setCover((String) map.get("cover"));
                        item.setFreeflag(Integer.valueOf((String) map.get("freeflag")));
                        item.setNotepath((String) map.get("notepath"));
                        item.setPrice(Double.valueOf((String) map.get("price")));
                        item.setSpeaker((String) map.get("speaker"));
                        item.setUploadate(Utils.getDateFromTimestamp(map.get("uploaddate")));
                        item.setVideodesc((String) map.get("videodesc"));
                        item.setVideoid(Integer.valueOf((String) map.get("videoid")));
                        item.setVideoname((String) map.get("videoname"));
                        item.setVideopath((String) map.get("videopath"));
                        item.setVideotype((String) map.get("videotype"));
                        videoItems.add(item);

                    }
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
                notifyDataSetChanged(videoItems);
            }
        }).start();
    }

    /**
     * 点击收藏图标
     *
     * @param view
     */
    public void collectClick(View view) {
        final Context context = getContext();
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                if (collectflag) {
                    count = WebApi.removeCollection(context, "v", video.getVideoid());
                } else {
                    count = WebApi.addCollection(context, "v", video.getVideoid());

                }
                if (count >= 0) {
                    setCollectflag(!collectflag);
                    setCollect(count);
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 点赞
     *
     * @param view
     */
    public void likeClick(View view) {
        final Context context = getContext();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = WebApi.addLikeVideo(context, video.getVideoid());

                if (count >= 0) {
                    setLikeflag(true);
                    setVideolike(count);
                }
            }
        }).start();
    }

    /**
     * 分享
     *
     * @param view
     */
    public void shareClick(View view) {
        Activity activity = (Activity) getContext();
        ShareModel model = new ShareModel(activity);
        model.setShareType("video");
        model.setId(video.getVideoid());
        model.setShareCallback(new ShareModel.Callback() {
            @Override
            public void onShareSuccess() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int count = WebApi.videoShare(getContext(), getVideo().getVideoid());
                        if (count >= 0) {
                            setVideoshare(count);
                        }
                    }
                }).start();
            }

            @Override
            public void onShare(ShareItem shareItem) {
                ShareContent content = new ShareContent();
                content.mTitle = ShareModel.SHARE_TITLE;
                content.mText = ShareModel.SHARE_TEXT;
                content.mTargetUrl = WebApi.getShareUrl();
                content.mMedia = new UMImage(getContext(), ShareModel.SHARE_IMG);
                shareItem.setShareData(content);
            }
        });
        PopupActivity.startActivity(activity, R.layout.v_dialog_share, BR.share, model);
    }

    /**
     * 点击添加关注
     *
     * @param view
     */
    public void addAttention(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (attentionFlag) {
                    if (WebApi.unAttention(getContext(), getVideo().getUid())) {
                        setAttentionFlag(false);
                    }
                } else {
                    if (WebApi.addAttention(getContext(), getVideo().getUid())) {
                        setAttentionFlag(true);
                    }
                }
            }
        }).start();
    }

    /**
     * 发表评论
     *
     * @param view
     */
    public void onSendComment(View view) {
        if (Utils.isNullOrEmpty(getCommentContent())) {
            showToast("评论内容不能为空");
            return;
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!WebApi.allowAction(getContext())) {
                    LoadingDialog.getInstance(getContext()).dismiss();
                    return;
                }
                if (WebApi.sendComment(getContext(), getVideo().getVideoid(), "v", getCommentContent())) {
                    setCommentContent("");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadCommentList();
                        }
                    });
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    public void onClickAvatar(View view) {
        HomeActivity.showPersonalCentral(getContext(), video.getUid());
    }
}
